package org.ffmmx.common.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ffmmx.ybb.model.Ok;
import org.ffmmx.ybb.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@CacheConfig(cacheNames = "captcha")
@RequestMapping("/api/captcha")
public class CommonController {
    Log log = LogFactory.getLog(this.getClass());

    @Autowired
    private DefaultKaptcha kaptcha;
    @Autowired
    private CacheManager cacheManager;
    private String cacheName = "captcha";

    /**
     * 获取验证码
     *
     * @return
     */
    @RequestMapping(value = "/fetch",method = RequestMethod.GET)
    public Result<Map<String, String>> captcha() {
        final Map<String, String> rst = new HashMap<>();
        String captchaKey = UUID.randomUUID().toString();
        String captchaCode = kaptcha.createText();
        BufferedImage captchaImage = kaptcha.createImage(captchaCode);
        final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            ImageIO.write(captchaImage, "jpg", byteArrayOutputStream);
        } catch (IOException e) {

            final Result result = new Result();
            result.setCode(1);
            result.setException(e);
            result.setMsg(e.getMessage());
            result.setSuccess(false);

            log.error(e);
            return result;
        }
        final String captchaImageEncode = Base64Utils.encodeToString(byteArrayOutputStream.toByteArray());

        rst.put("captchaKey", captchaKey);
        rst.put("captchaImage", captchaImageEncode);
        saveCaptchaCodeToCache(captchaKey, captchaCode);
        return new Ok(rst);
    }

    public void saveCaptchaCodeToCache(String ckey, String ccode) {
        cacheManager.getCache("captcha").put(ckey, ccode);
    }

    /**
     * 遗忘验证码
     *
     * @param ckey
     * @return
     */
    @RequestMapping(value = "/forget",method = RequestMethod.POST)
    public Result<Map<String, String>> evictCaptchaCode(@RequestParam String ckey) {
        final Map<String, String> map = new HashMap<>();
        cacheManager.getCache("captcha").evict(ckey);
        return new Ok<>(map);
    }

}
